<?php


if (!defined('IN_SEXMALL'))
{
	die('Hacking attempt');
}

define('WAP_ADMIN', true);

error_reporting(E_ALL);

if (__FILE__ == '')
{
	die('Fatal error code: 0');
}

/* 初始化设置 */
@ini_set('memory_limit',          '264M');
@ini_set('session.cache_expire',  180);
@ini_set('session.use_trans_sid', 0);
@ini_set('session.use_cookies',   1);
@ini_set('session.auto_start',    0);
@ini_set('display_errors',        1);

if (DIRECTORY_SEPARATOR == '\\')
{
	@ini_set('include_path',      '.;' . ROOT_PATH);
}
else
{
	@ini_set('include_path',      '.:' . ROOT_PATH);
}

/* 取得当前所在的根目录 */
if(!defined('ADMIN_PATH'))
{
	define('ADMIN_PATH','admin');
}
define('ROOT_PATH', str_replace(ADMIN_PATH . '/includes/init.php', '', str_replace('\\', '/', __FILE__)));

/* 配置文件目录 */
define('CONF_DIR', ROOT_PATH . 'config/');
define('TEMP_DIR', ROOT_PATH . 'temp/');	// 临时目录

define('DATA_DIR', 'data');
define('IMAGE_DIR', 'images');

/* 加载项目配置文件 */
require(CONF_DIR . 'base.config.php');
require(CONF_DIR . 'db.config.php');


if (defined('DEBUG_MODE') == false)
{
	define('DEBUG_MODE', 0);
}

if (PHP_VERSION >= '5.1' && !empty($timezone))
{
	date_default_timezone_set($timezone);
}

if (isset($_SERVER['PHP_SELF']))
{
	define('PHP_SELF', $_SERVER['PHP_SELF']);
}
else
{
	define('PHP_SELF', $_SERVER['SCRIPT_NAME']);
}

require(ROOT_PATH . 'includes/inc_constant.php');
require(ROOT_PATH . 'includes/cls_error.php');
require(ROOT_PATH . 'includes/lib_time.php');
require(ROOT_PATH . 'includes/lib_code.php');
require(ROOT_PATH . 'includes/lib_base.php');
require(ROOT_PATH . 'includes/lib_common.php');
require(ROOT_PATH . 'includes/lib_interface.php');
require(ROOT_PATH . 'includes/lib_main.php');
require(ROOT_PATH . ADMIN_PATH . '/includes/lib_main.php');
require(ROOT_PATH . ADMIN_PATH . '/includes/lib_common.php');
require(ROOT_PATH . ADMIN_PATH . '/includes/cls_exchange.php');
require(ROOT_PATH . 'includes/MemcacheModel.class.php');
require(ROOT_PATH . 'includes/MInterface.class.php');

/* 初始化数据库类 */
require(ROOT_PATH . 'includes/cls_mysql.php');
$db = new cls_mysql(DBHOST, DBUSER, DBPWD, DBNAME);

/* 初始化session */
require(ROOT_PATH . 'includes/cls_session.php');
$sess = new cls_session('ADMIN_ID');
define('SESS_ID', $sess->get_session_id());

/* 读取配置 */
$_CFG = load_config();

require(CONF_DIR . 'define.config.php');

/* 创建 Memcache 对象 */
ini_set("memcache.hash_strategy", "consistent");
$mem = new MemcacheModel($memServers);

// 实例化b2c接口对象
$mInterface = new MInterface($api_server);

/* 对用户传入的变量进行转义操作。*/
if (!get_magic_quotes_gpc())
{
	if (!empty($_GET))
	{
		$_GET  = addslashes_deep($_GET);
	}
	if (!empty($_POST))
	{
		$_POST = addslashes_deep($_POST);
	}

	$_COOKIE   = addslashes_deep($_COOKIE);
	$_REQUEST  = addslashes_deep($_REQUEST);
}

/* 对路径进行安全处理 */
if (strpos(PHP_SELF, '.php/') !== false)
{
	wap_header("Location:" . substr(PHP_SELF, 0, strpos(PHP_SELF, '.php/') + 4) . "\n");
	exit();
}


/* 创建错误处理对象 */
$err = new wap_error('message.htm');


/* 初始化 action */
if (!isset($_REQUEST['act']))
{
	$_REQUEST['act'] = '';
}
elseif (($_REQUEST['act'] == 'login' || $_REQUEST['act'] == 'logout' || $_REQUEST['act'] == 'signin') &&
strpos(PHP_SELF, '/privilege.php') === false)
{
	$_REQUEST['act'] = '';
}
elseif (($_REQUEST['act'] == 'forget_pwd' || $_REQUEST['act'] == 'reset_pwd' || $_REQUEST['act'] == 'get_pwd') &&
strpos(PHP_SELF, '/get_password.php') === false)
{
	$_REQUEST['act'] = '';
}


// 登录部分准备拿出去做，到时候把以下操作一起挪过去
if ($_REQUEST['act'] == 'captcha')
{
	include(ROOT_PATH . 'includes/cls_captcha.php');

	$img = new captcha('../data/captcha/');
	@ob_end_clean(); //清除之前出现的多余输入
	$img->generate_image();

	exit;
}

require(ROOT_PATH . 'languages/' .$_CFG['lang']. '/'.ADMIN_PATH.'/common.php');
require(ROOT_PATH . 'languages/' .$_CFG['lang']. '/'.ADMIN_PATH.'/log_action.php');
if (file_exists(ROOT_PATH . 'languages/' . $_CFG['lang'] . '/'.ADMIN_PATH.'/' . basename(PHP_SELF)))
{
	include(ROOT_PATH . 'languages/' . $_CFG['lang'] . '/'.ADMIN_PATH.'/' . basename(PHP_SELF));
}

if (!file_exists('../temp/'.ADMIN_PATH.'/caches'))
{
	@mkdir('../temp/'.ADMIN_PATH.'/caches', 0777);
	@chmod('../temp/'.ADMIN_PATH.'/caches', 0777);
}

if (!file_exists('../temp/'.ADMIN_PATH.'/compiled'))
{
	@mkdir('../temp/'.ADMIN_PATH.'/compiled', 0777);
	@chmod('../temp/'.ADMIN_PATH.'/compiled', 0777);
}

clearstatcache();


/* 创建 Smarty 对象。*/
require(ROOT_PATH . 'includes/cls_template.php');
$smarty = new cls_template;

$smarty->template_dir  = ROOT_PATH . ADMIN_PATH . '/templates';
$smarty->compile_dir   = ROOT_PATH . 'temp/'.ADMIN_PATH.'/compiled';
if ((DEBUG_MODE & 2) == 2)
{
	$smarty->force_compile = true;
}


$smarty->assign('lang', $_LANG);


// 验证管理员身份
$admin_id = $mem->getCache('admin_id');

if ((!isset($admin_id) || intval($admin_id) <= 0) &&
$_REQUEST['act'] != 'login' && $_REQUEST['act'] != 'signin' &&
$_REQUEST['act'] != 'forget_pwd' && $_REQUEST['act'] != 'reset_pwd')
{
	//* session 不存在，检查cookie //
	if (!empty($_COOKIE['SEXMALL']['admin_id']) && !empty($_COOKIE['SEXMALL']['admin_pass']))
	{
		// 找到了cookie, 验证cookie信息
		$sql = 'SELECT user_id, user_name, password, action_list, last_login ' .
                ' FROM ' .TABLEPRE .
                "admin_user WHERE user_id = '" . intval($_COOKIE['SEXMALL']['admin_id']) . "'";
		$row = $db->GetRow($sql);

		if (!$row)
		{
			// 没有找到这个记录
			setcookie($_COOKIE['SEXMALL']['admin_id'],   '', 1);
			setcookie($_COOKIE['SEXMALL']['admin_pass'], '', 1);

			if (!empty($_REQUEST['is_ajax']))
			{
				make_json_error($_LANG['priv_error']);
			}
			else
			{
				wap_header("Location: privilege.php?act=login\n");
			}

			exit;
		}
		else
		{
			// 检查密码是否正确
			if (md5($row['password'] . $_CFG['hash_code']) == $_COOKIE['SEXMALL']['admin_pass'])
			{
				!isset($row['last_time']) && $row['last_time'] = '';
				set_admin_session($row['user_id'], $row['user_name'], $row['action_list'], $row['last_time']);

				// 更新最后登录时间和IP
				$db->query('UPDATE ' . TABLEPRE . "admin_user ".
                            " SET last_login = '" . local_time() . "', last_ip = '" . real_ip() . "'" .
                            " WHERE user_id = '" . $admin_id . "'");
			}
			else
			{
				setcookie($_COOKIE['SEXMALL']['admin_id'],   '', 1);
				setcookie($_COOKIE['SEXMALL']['admin_pass'], '', 1);

				if (!empty($_REQUEST['is_ajax']))
				{
					make_json_error($_LANG['priv_error']);
				}
				else
				{
					wap_header("Location: privilege.php?act=login\n");
				}

				exit;
			}
		}
	}
	else
	{
		if (!empty($_REQUEST['is_ajax']))
		{
			make_json_error($_LANG['priv_error']);
		}
		else
		{
			wap_header("Location: privilege.php?act=login\n");
		}

		exit;
	}
}

if ($_REQUEST['act'] != 'login' && $_REQUEST['act'] != 'signin' &&
$_REQUEST['act'] != 'forget_pwd' && $_REQUEST['act'] != 'reset_pwd' && $_REQUEST['act'] != 'check_order')
{
	$admin_path = preg_replace('/:\d+/', '', get_url()) . ADMIN_PATH;
	if (!empty($_SERVER['HTTP_REFERER']) &&
	strpos(preg_replace('/:\d+/', '', htmlspecialchars($_SERVER['HTTP_REFERER'])), $admin_path) === false)
	{
		if (!empty($_REQUEST['is_ajax']))
		{
			make_json_error($_LANG['priv_error']);
		}
		else
		{
			wap_header("Location: privilege.php?act=login\n");
		}

		exit;
	}
}

/* 管理员登录后可在任何页面使用 act=phpinfo 显示 phpinfo() 信息 */
if ($_REQUEST['act'] == 'phpinfo' && function_exists('phpinfo'))
{
	phpinfo();

	exit;
}

//header('Cache-control: private');
header('content-type: text/html; charset=' . CHARSET);
header('Expires: Fri, 14 Mar 1980 20:53:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-cache, must-revalidate');
header('Pragma: no-cache');

if ((DEBUG_MODE & 1) == 1)
{
	error_reporting(E_ALL);
}
else
{
	error_reporting(E_ALL ^ E_NOTICE);
}
if ((DEBUG_MODE & 4) == 4)
{
	include(ROOT_PATH . 'includes/lib.debug.php');
}

/* 判断是否支持gzip模式 */
if (gzip_enabled())
{
	ob_start('ob_gzhandler');
}
else
{
	ob_start();
}

?>
